package tree;

import java.util.List;

/** 
 * 节点归并类 
 * @author bearsmall 
 * 
 */  
public class TreeNodeMerger {  
  
    /** 
     * 将节点数组归并为一棵树（填充节点的children域） 
     * 时间复杂度为O(n^2) 
     * @param items 节点域 
     * @return 
     */  
    public static TreeNode merge(TreeNode[] items){  
        TreeNodeManager treeNodeManager = new TreeNodeManager(items);  
        for (TreeNode treeNode : items) {  
            if(!treeNode.getPid().equals("0")){  
                TreeNode t = treeNodeManager.getTreeNodeAT(treeNode.getPid());  
                t.getChildren().add(treeNode);  
            }  
        }  
        return treeNodeManager.getRoot();  
    }  
      
    /** 
     * 将节点数组归并为一棵树（填充节点的children域） 
     *  时间复杂度为O(n^2) 
     * @param items 节点域 
     * @return 
     */  
    public static TreeNode merge(List<TreeNode> items){  
        TreeNodeManager treeNodeManager = new TreeNodeManager(items);  
        for (TreeNode treeNode : items) {  
            if(!treeNode.getPid().equals("0")){
//            if(!treeNode.getPid().equals("-1")){
                TreeNode t = treeNodeManager.getTreeNodeAT(treeNode.getPid());  
                t.getChildren().add(treeNode);  
            }  
        }  
        return treeNodeManager.getRoot();  
    }  
}